package com.mall.order.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.mall.order.OrderPromoService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateSeckillOrderRequest;
import com.mall.order.dto.CreateSeckillOrderResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

@Component
@Transactional
public class PromoOrderConsumer {
    private DefaultMQPushConsumer consumer;

    @Reference
    OrderPromoService orderPromoService;
    @PostConstruct
    public void init(){
        consumer = new DefaultMQPushConsumer("promo-order-consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        try {
            consumer.subscribe("createPromoOrder","*");
            consumer.setMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    //消费消息,创建秒杀订单
                    MessageExt msg = list.get(0);
                    String msgBody = new String(msg.getBody(), Charset.forName("utf-8"));
                    CreateSeckillOrderRequest request = JSON.parseObject(msgBody, CreateSeckillOrderRequest.class);
                    CreateSeckillOrderResponse response = orderPromoService.createPromoOrder(request);
                    if(!OrderRetCode.SUCCESS.getCode().equals(response.getCode())){
                        //订单事务失败回滚,重试消费
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }
}
